﻿using BasicModuleWebApiAuthorization.Model;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Security.Cryptography.Xml;

namespace BasicModuleWebApiAuthorization.Controllers
{
    [ApiController]
    [Route("api/[controller]/Product")]
    public class ProductController : ControllerBase
    {
        [Route("Index")]
        [HttpGet]
        [Authorize("usernames")]
        public string Index()
        {

            return "xxxxx";
        }

        [Route("Login")]
        [HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            var data = HttpContext.User;
            //创建身份ClaimsIdentity
            //创建声明 用户的描述 用户名 密码、角色
            Claim[] claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, user.Name),
                new Claim("Passwd", user.Passwd),
                new Claim("UserRole",user.Role)
            };
            //创建身份
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            //实现登录
            AuthenticationProperties authenticationProperties = new AuthenticationProperties();
            //设置过期时间
            authenticationProperties.IsPersistent = true;
            authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(1);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
            //await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authenticationProperties);
            //return Unauthorized("失败");
            return Ok("成功");
        }

        [Route("User")]
        [Authorize("user")]
        [HttpGet]
        public void Getuser()
        {
            string claem = HttpContext.User.Identity.Name;
            var claims = HttpContext.User.Claims;
            var xx = HttpContext.User.Claims.Where(x => x.Type == "Passwd").FirstOrDefault();
            string yy = xx.Value;
        }
    }
}
